﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using rentit03_server.Database;

namespace rentit03_server.Business
{
    public static class MediaFileCreator
    {
        /// <summary>
        /// Creates a file representing a medium and return the url to the file
        /// </summary>
        /// <param name="media">The media used to create the file</param>
        /// <returns>URL to the file</returns>
        public static string GetMediaFile(Media media)
        {
            var fileName =  @String.Concat(media.Title.Trim().Split(' '));
            //fileName = fileName.Replace(":", "");
            fileName = Regex.Replace(fileName, "[^A-Za-z0-9]", "") + ".txt";
            var path = @"C:\RentItServices\RentIt03\downloads\" + fileName;
            var url = @"http://rentit.itu.dk/rentit03/downloads/" + fileName;

            var fileBody = new StringBuilder();
            fileBody.AppendLine(media.Title + " (" + media.Year + ")");
            fileBody.AppendLine();
            fileBody.AppendLine("Description:");
            fileBody.AppendLine(media.Description);

            // Delete the file if it exists.
            if (File.Exists(path))
            {
                File.Delete(path);
                //alt
                //return url;
            }

            // Create the file.
            try
            {
                using (FileStream fs = File.Create(path, 1024))
                {
                    Byte[] content = new UTF8Encoding(true).GetBytes(fileBody.ToString());
                    // Add some information to the file.
                    fs.Write(content, 0, content.Length);
                }
            }
            catch (Exception e)
            {
                throw new RentitException("MediaFileCreator.cs - The given path's format is not supported: " + path, e);
            }
            
            // Open the stream and read it back.
            // Not used. Just for reference.
            /*using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }*/

            return url;
        }
    }
}